<template>
  <view class="bg-fff">
    <view
        class=" mb-2 p-2 color-92 "
    >
      <view class="py-1 font30 font-bold text-center">{{ newsItem.title }}</view>
      <view class="font26">
        {{ newsItem.content }}
      </view>
      <view class="d-flex d-flex-between py-2 font20">
        <text>发布人：{{ newsItem.editor_name }}</text>
        <text> {{ newsItem.created_at }}</text>
      </view>
      <image
          class="rounded10"
          mode="widthFix"
          :src="newsItem.image"
      ></image>
    </view>

    <view class="pb-7 ">
      <view class="main-color font32 font-bold px-4 pb-4">全部评论</view>

      <view v-if="comments && comments.length > 0" class="d-flex comment-divider pb-2 mb-4 mx-4"
            v-for="(item,index) in comments" :key="index">
        <image class="avatar-image" :src="item?.user?.avatar" mode="aspectFill"></image>
        <view class="ml-2 d-flex-item">
          <view class="d-flex d-flex-between">
            <text class="color-92">{{ item?.user?.name }}</text>
            <text
                class="iconfont icon-shenglvehao font40 main-color"
                @click="toggleCommentActions(item,index)"
            ></text>
          </view>
          <view class="pt-1 pb-2 font20" style="color: rgba(92, 92, 92, 0.6)">{{ item.created_at }}</view>
          <view class="color-92 pb-3 font26">{{ item.content }}</view>
          <view class="d-flex d-flex-between">
            <text class="d-flex-2 color-92 font20" @click="goReplyPopup(item, item.user)">回复</text>
            <view class="d-flex d-flex-between d-flex-middle d-flex-item">
              <text class="iconfont icon-dianzan"></text>
              <view class="rotate180">
                <text class="iconfont icon-dianzan "></text>
              </view>
            </view>
          </view>
          <view v-if="item.total_replies>0"
                class="mt-2 bg-fff px-2 py-1 font20 color-92 rounded10 d-flex d-flex-middle"
                style="color: rgba(92, 92, 92, 0.6)"
                @click="toggleCommentReplies(index, item.id)">
            {{ expandedComments.has(index) ? '收起' : '展开' }}{{ item.total_replies }}条回复
            <text
                :class="['font30', 'iconfont', expandedComments.has(index) ? 'icon-jiantou_liebiaoshouqi_o' : 'icon-jiantou_liebiaozhankai_o', 'font-bold']"></text>
          </view>

          <!-- 回复列表展示区域 -->
          <view v-if="expandedComments.has(index) && item.replies" class="replies-container pl-4">
            <view v-for="(reply, replyIndex) in item.replies" :key="replyIndex" class="reply-item py-2">
              <view class="d-flex">
                <image class="avatar-image small" :src="reply?.user?.avatar || '/static/default-avatar.png'"
                       mode="aspectFill"></image>
                <view class="ml-2 flex-1">
                  <view class="font24" style="color: rgba(92, 92, 92, 0.4)">{{ reply?.user?.name || '匿名用户' }}
                    <text class="iconfont icon-Rrl_s_048 font20"></text>
                    {{ reply?.reply_to_user?.name || '匿名用户' }}
                  </view>
                  <view class="font24 color-92 my-1">{{ reply.content }}</view>
                  <view class="font20" style="color: rgba(92, 92, 92, 0.4)">
                    <text>{{ reply.created_at }}</text>
                    <text class="d-flex-2 color-92 font20 ml-3" @click="goReplyPopup(reply, reply.user)">回复</text>

                  </view>
                </view>
              </view>
            </view>
            <!-- 添加展开更多按钮 -->
            <view v-if="item.has_more_replies"
                  class="more-replies-btn text-center py-2 color-92 font24"
                  @click="loadMoreReplies(item.id)">
              展开更多回复
              <text class="iconfont icon-jiantou_liebiaozhankai_o ml-1"></text>
            </view>

          </view>
        </view>
      </view>

      <view v-else class="load-more d-flex d-flex-center d-flex-column d-flex-middle">
        <image class="mb-2" v-if="loadingType == 2 && comments.length == 0"
               src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/formal/images/empty.png"
               style="width: 198rpx;height: 128rpx;margin-top: 260rpx;"></image>
        <text class="font24">
          {{ loadingType === 0 ? '上拉显示更多' : (loadingType === 1 ? '正在加载...' : '暂无评论，欢迎来评论') }}
        </text>
      </view>

    </view>

    <view class="fixedBtn bg-fff pt-2 px-2 pb-5 d-flex d-flex-between font24  d-flex-middle">
      <view class="d-flex d-flex-between d-flex-item">
        <view class="input-container d-flex d-flex-middle" @click="goReplyPopup()">
          <input
              class="comment-input rounded40"
              type="text"
              placeholder="留下点什么吧..."
              placeholder-style="color: rgba(92, 92, 92, 0.6)"
              v-model="replyContent"
          />
          <view class="iconfont icon-xiaolian main-color font56 ml-2"></view>
        </view>
      </view>
      <view class="d-flex d-flex-middle ml-2">
        <view>
          <text class="iconfont icon-shoucang coloryellow font40"></text>
          <text class=" font24">123</text>
        </view>
        <view class="font24 ml-2">
          <text class="iconfont icon-aixin1 colorf00 font50 "></text>
          <text class=" ">123</text>
        </view>
      </view>
    </view>

    <uni-popup
        ref="replyPopup"
        type="bottom"
        :safe-area="false"
        mode="bottom"
        :safeAreaInsetBottom="false"
        @close="closeReplyPopup"
        :animation="true"
    >
      <view class="reply-popup-content">
        <view class="popup-header">
          <text @click="closeReplyPopup">取消</text>
          <text :class="{ 'active': replyContent.trim() }" @click="submitReply">发布</text>
        </view>
        <view class="popup-input-container">
          <input
              v-model="replyContent"
              :placeholder="'回复 @' + (currentReplyUser?.name || '用户')"
              :focus="isPopupOpen"
              @confirm="submitReply"
              :cursor-spacing="20"
              :adjust-position="true"
              :show-confirm-bar="false"
          />
        </view>
      </view>
    </uni-popup>

    <uni-popup ref="commentActionsPopup" type="bottom" :safe-area="false">
      <view class="comment-actions-popup">
        <view class="popup-content">
          <view class="popup-item bg-fff main-color" @click="handleDeleteComment">删除</view>
          <view class="popup-item bg-fff" @click="handleReplyComment">回复</view>
          <view class="popup-item mt-2 cancel-item bg-fff pb-5" @click="closeCommentActions">取消</view>
        </view>
      </view>
    </uni-popup>

  </view>
</template>

<script>
import {
  mapState
} from "vuex"
import {homeApi} from "@/http/homeApi";

export default {
  data() {
    return {
      newsItem: {},
      comments: [], //主数据
      cIndex: 0,//0 代表主新增，1代表子新增
      expandedComments: new Set(),
      replyContent: '',
      currentReplyComment: null,
      currentReplyUser: null,
      isPopupOpen: false,
      twoCommentId: '',
      currentPage: 1,
      page: 1,
      loadingType: 1,
      // 删除评论的弹窗
      showCommentActions: false,
      selectedComment: null,
      selectedCommentIndex: -1
    }
  },
  computed: {
    ...mapState({
      statusBarHeight: state => state.statusBarHeight,
      menuButtonHeight: state => state.menuButtonHeight,
      titleBarHeight: state => state.titleBarHeight,
      avatar: state => state.avatar,
      loginState: state => state.loginState
    })
  },
  onLoad(options) {
    // 获取上一页传递的参数
    if (options && options.id) {
      this.comments = []
      this.page = 1;
      this.currentPage = 1;
      this.newsId = options.id;
      // 根据ID获取对应的新闻详情
      this.goNotifications2(options.id);
      this.goNotificationsComments(options.id)
    } else {
      // 如果没有传ID，使用默认数据或显示错误提示
      this.goNotifications2();
    }

  },

  onReachBottom() {
    if (this.loadingType == 2 || this.loadingType == 1) {
      return;
    }
    this.currentPage++
    this.goNotificationsComments(this.newsItem.id);
  },
  methods: {
    async goNotifications2(id) {
      try {
        let res = await homeApi.getNotificationsId(id);
        if (res) {
          this.newsItem = res;
        }
      } catch (error) {
        console.error('获取新闻详情失败:', error);
      }
    },
    async goNotificationsComments(id, data) {
      this.loadingType = 1
      try {
        let params = {
          id: id,
          page: this.currentPage
        }
        let res = await homeApi.getNotificationsComments(params);
        if (this.twoCommentId && data) {
          // 走添加回复列表
          this.loadMoreReplies(this.twoCommentId, this.page)
        } else {
          if (res.list) {
            if (this.currentPage === 1) {
              this.comments = res.list;
            } else {
              this.comments = this.comments.concat(res.list);
            }
          }
          if (res.list && res.list.length > 9) {
            this.loadingType = 0
          } else {
            this.loadingType = 2
          }
        }

      } catch (error) {
        this.loadingType = 2

        console.error('获取新闻详情失败:', error);
      }
    },
    // 切换评论回复的展开状态
    async toggleCommentReplies(commentIndex, commentId) {
      if (this.expandedComments.has(commentIndex)) {
        // 如果已展开，则收起
        this.expandedComments.delete(commentIndex);
      } else {
        // 如果未展开，则展开
        this.expandedComments.add(commentIndex);
        // 首次展开时加载回复数据
        if (!this.comments[commentIndex].replies) {
          await this.loadCommentReplies(commentIndex, commentId);
        }
      }
    },

    // 加载评论回复数据
    async loadCommentReplies(commentIndex, commentId) {
      try {
        const res = await homeApi.getCommentReplies(commentId);
        if (res && res.list) {
          // 使用Vue.set确保响应式更新
          this.$set(this.comments[commentIndex], 'replies', res.list);
        }
      } catch (error) {
        console.error('加载评论回复失败:', error);
        uni.showToast({
          title: '加载回复失败',
          icon: 'none'
        });
      }
    },
    // 加载更多回复
    async loadMoreReplies(commentId, oldPage) {
      try {
        // 获得2级里面的id
        this.twoCommentId = commentId
        // 查找对应的评论索引
        const commentIndex = this.comments.findIndex(comment => comment.id === commentId);
        if (commentIndex === -1) {
          console.error('未找到对应的评论');
          return;
        }

        // 获取当前评论的分页信息
        const currentPage = this.comments[commentIndex].reply_page || 1;
        console.log(currentPage)

        if (oldPage) {
          this.page = oldPage
        } else {
          this.page = currentPage
        }

        let params = {
          id: commentId,
          page: this.page
        }

        const res = await homeApi.getCommentsReplies(params);
        if (res && res.list) {
          // 获取当前已有的回复
          const currentReplies = this.comments[commentIndex].replies || [];

          // 追加新加载的回复到现有回复列表中
          const updatedReplies = [...currentReplies, ...res.list];
          this.$set(this.comments[commentIndex], 'replies', updatedReplies);

          // 更新分页信息
          this.$set(this.comments[commentIndex], 'reply_page', this.page + 1);

          // 更新 has_more_replies 状态
          this.$set(this.comments[commentIndex], 'has_more_replies', res.has_more);
        }
      } catch (error) {
        console.error('加载更多回复失败:', error);
        uni.showToast({
          title: '加载更多回复失败',
          icon: 'none'
        });
      }
    },
    goUrl(urlPages, data) {
      if (!this.loginState) {
        uni.showToast({
          title: '未登录，请先登录！',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/subPages/login/login'
          })
        }, 1500)
      } else {
        uni.navigateTo({
          url: urlPages
        })
      }
    },
    // 提交回复
    async submitReply() {
      if (!this.replyContent.trim()) {
        uni.showToast({
          title: '请输入回复内容',
          icon: 'none'
        });
        return;
      }

      try {
        const params = {
          notification_id: this.newsItem.id,
          content: this.replyContent.trim(),
          parent_id: this.currentReplyComment?.id || ''
        };

        // 调用API提交回复
        const res = await homeApi.notificationsComments(params);

        uni.showToast({
          title: '回复成功',
          icon: 'success'
        });

        console.log(this.cIndex,'666')

        if (this.cIndex ==0) {
          // 主评论新增 - 添加到评论列表开头
          if (res) {
            this.comments.unshift(res);
          }
        }else if (this.cIndex ==1) {
          if (res) {
            // 查找父评论的索引（包括一级和二级评论）
            let parentIndex = this.comments.findIndex(comment =>
                comment.id === this.currentReplyComment.id ||
                comment.id === this.currentReplyComment.parent_id
            );

            // 如果在一级评论中没找到，继续在二级回复中查找
            if (parentIndex === -1) {
              for (let i = 0; i < this.comments.length; i++) {
                const comment = this.comments[i];
                if (comment.replies && Array.isArray(comment.replies)) {
                  const replyIndex = comment.replies.findIndex(reply =>
                      reply.id === this.currentReplyComment.id ||
                      reply.id === this.currentReplyComment.parent_id
                  );
                  if (replyIndex !== -1) {
                    parentIndex = i; // 找到二级评论，返回其所属的一级评论索引
                    break;
                  }
                }
              }
            }

            if (parentIndex !== -1) {
              // 确保 replies 数组存在
              if (!this.comments[parentIndex].replies) {
                this.$set(this.comments[parentIndex], 'replies', []);
              }
              // 添加新回复到父评论的回复列表
              this.comments[parentIndex].replies.push(res);
              // 更新回复计数
              this.$set(this.comments[parentIndex], 'total_replies',
                  (this.comments[parentIndex].total_replies || 0) + 1);
              // console.log(this.comments[parentIndex])
            }
          }
        }

        this.closeReplyPopup();
        // 重新加载评论列表
        // this.goNotificationsComments(this.newsItem.id, res);

      } catch (error) {
        console.error('回复失败:', error);
        uni.showToast({
          title: '回复失败',
          icon: 'none'
        });
      }
    },
    goReplyPopup(comment, user) {
      if (!comment) {
        this.cIndex = 0; // 主评论新增
      } else {
        this.cIndex = 1; // 子评论回复
      }
      this.currentReplyComment = comment;
      this.currentReplyUser = user;

      this.replyContent = '';
      this.isPopupOpen = false;

      this.$nextTick(() => {
        if (this.$refs.replyPopup) {
          this.$refs.replyPopup.open();
          // 使用更精确的延时和重试机制
          const focusInput = () => {
            setTimeout(() => {

              this.isPopupOpen = true;
            }, 300);
          };
          // 首次尝试
          focusInput();
        }
      });
    },

    closeReplyPopup() {
      this.isPopupOpen = false;
      if (this.$refs.replyPopup) {
        this.$refs.replyPopup.close();
      }
      this.replyContent = '';
      this.currentReplyComment = null;
      this.currentReplyUser = null;
    },
    //   删除评论
    toggleCommentActions(comment, index) {
      this.selectedComment = comment;
      this.selectedCommentIndex = index;
      if (this.$refs.commentActionsPopup) {
        this.$refs.commentActionsPopup.open();
      }
    },

    // 关闭弹窗
    closeCommentActions() {
      if (this.$refs.commentActionsPopup) {
        this.$refs.commentActionsPopup.close();
      }
    },

    // 处理删除评论
    handleDeleteComment() {
      if (!this.selectedComment) return;

      uni.showModal({
        title: '提示',
        content: '确定要删除这条评论吗？',
        success: (res) => {
          if (res.confirm) {
            this.performDeleteComment();
          }
        }
      });
    },

    // 执行删除评论操作
    async performDeleteComment() {
      try {
        // 调用删除API
        console.log(this.selectedComment.id, 'this.selectedComment.id')
        await homeApi.delComments({id: this.selectedComment.id});

        // 从本地列表中移除
        this.comments.splice(this.selectedCommentIndex, 1);

        uni.showToast({
          title: '删除成功',
          icon: 'success'
        });

        this.closeCommentActions();
      } catch (error) {
        console.error('删除评论失败:', error);
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        });
      }
    },

    // 处理回复评论
    handleReplyComment() {
      // 先干掉
      this.closeCommentActions();
      if (this.selectedComment) {
        this.goReplyPopup(this.selectedComment, this.selectedComment.user);
      }
    },
  }
}
</script>

<style scoped>
.color-92 {
  color: rgba(92, 92, 92, 1);
}


.news-image {
  height: 228rpx;
  width: 100%;
  display: block;
  margin: 0 auto;
  background-color: rgba(204, 204, 204, 1);
}

.comment-divider {
  border-bottom: 1px solid rgba(92, 92, 92, 0.2);
}

.color-92 {
  color: rgba(92, 92, 92, 1);
}

.d-flex-2 {
  flex: 2;
}

.avatar-image {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  border: 4rpx solid rgba(171, 206, 255, 1);
}

.fixedBtn {
  position: fixed;
  bottom: 0;
  width: calc(100% - 40rpx);
  border-top: 10rpx solid rgba(235, 235, 235, 1);
}


.input-container {
  background-color: rgba(235, 235, 235, 1);
  padding: 10rpx 20rpx;
  border-radius: 40rpx;
  width: 100%;
}

.comment-input {
  flex: 1;
  font-size: 24rpx;
  background-color: transparent; /* 修改背景色为透明 */
}

.pb-7 {
  padding-bottom: 160rpx;
}

.small {
  width: 30rpx;
  height: 30rpx;
}

.replies-container {
  background-color: #f8f8f8;
  border-radius: 10rpx;
  margin-top: 10rpx;
}

.reply-item {
  border-bottom: 1px solid rgba(92, 92, 92, 0.1);
}

.reply-item:last-child {
  border-bottom: none;
}

.flex-1 {
  flex: 1;
}

.reply-popup-content {
  background-color: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  padding: 20rpx;
  overflow-y: auto;
  /* 移除 margin-bottom 或调整为 0 */
  margin-bottom: 0;
  /* 添加最小高度确保内容可见 */
  min-height: 200rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.popup-header text:last-child {
  color: #ccc;
  font-weight: bold;
}

.popup-header text:last-child.active {
  color: #3a7afe;
}

.popup-input-container input {
  padding: 20rpx;
  margin-top: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.more-replies-btn {
  color: #3a7afe;
  border-top: 1px solid rgba(92, 92, 92, 0.1);
  margin-top: 10rpx;
}

.comment-actions-popup {
  background-color: #f5f5f5;
}

.popup-content {
  padding: 20rpx;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  background-color: #fff;
}

.popup-item {
  padding: 30rpx;
  text-align: center;
  font-size: 28rpx;
  border-bottom: 1rpx solid #eee;
}

.popup-item:last-child {
  border-bottom: none;
}

.cancel-item {
  color: #999;
}
</style>
